package inc.gome.dynamic.datasource.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

/*服务端处理*/
public  class ServerRequestHandler extends ChannelInboundHandlerAdapter {

    Dispatcher dis;

    public ServerRequestHandler(Dispatcher dis) {
        this.dis=dis;
    }

    //provider:
    //思考下解决方法？
    //
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {



        //跑线程处理
        ctx.executor().execute(()->{
            //服务端执行响应给客户端
            try {
                System.out.println("服务端获取信息:"+msg);

                RequestBody requestPkg = (RequestBody) msg;  //请求体

                ResponseBody responseBody = new ResponseBody();
                responseBody.setRequestId(requestPkg.getRequestId());
                responseBody.setBody(requestPkg.getRequestId() + "_res");


                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ObjectOutputStream oout = new ObjectOutputStream(out);
                oout.writeObject(responseBody);


                byte[] bytes = out.toByteArray();
                //响应
                System.out.println(bytes.length);
                ctx.writeAndFlush(bytes);
            }catch (Exception e){
                e.printStackTrace();
            }
        });



    }

}